package com.zrwl.poscloud.base.utils;

import java.io.*;
import java.util.Date;

/**
 * @author 刘思童
 * @create 2021/1/25 21:59
 **/
public class GenerateCodeUtil {
    public static void createDir(String path) {
        File dir = new File(path);
        if (!dir.exists())
            dir.mkdir();
    }

    public static File createFile(String path, String filename, boolean overWrite) {
        File file = new File(path + "/" + filename);
        try {
            if (!file.exists())
                file.createNewFile();
            else {
                if (overWrite) {
                    file.delete();
                    file.createNewFile();
                } else {
                    Date now = new Date();
                    file = new File(path + "/" + filename + now.getTime());
                    file.createNewFile();
                }
            }
            return file;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void write(File file, String string) throws Exception {
        FileOutputStream out = null;
        out = new FileOutputStream(file, true);
        StringBuffer sb = new StringBuffer();
        sb.append(string + "\n");
        out.write(sb.toString().getBytes("utf-8"));
        out.close();
    }

    public static void doImport(File file, String className) throws Exception {
        insertStringInFile(file, 2, "import "+className + ";");
    }
    public static void doImport(File file, Object object) throws Exception {
        insertStringInFile(file, 2, "import "+object.getClass().getName() + ";");
    }
    public static void insertStringInFile(File file, int lineNo, String string) throws Exception {
        // 临时文件
        File outFile = File.createTempFile("name", ".tmp");

        // 输入
        FileInputStream fis = new FileInputStream(file);
        BufferedReader in = new BufferedReader(new InputStreamReader(fis));

        // 输出
        FileOutputStream fos = new FileOutputStream(outFile);
        PrintWriter out = new PrintWriter(fos);

        // 保存一行数据
        String thisLine;
        // 行号从1开始
        int i = 1;
        while ((thisLine = in.readLine()) != null) {
            // 如果行号等于目标行，则输出要插入的数据
            if (i == lineNo) {
                out.println(string);
            }
            // 输出读取到的数据
            out.println(thisLine);
            // 行号增加
            i++;
        }
        out.flush();
        out.close();
        in.close();
        fis.close();
        fos.close();
        // 删除原始文件
        boolean del= file.delete();
        // 把临时文件改名为原文件名
        boolean move=outFile.renameTo(file);
    }
}
